#include "GroupModel.hpp"
#include "mysqldb.hpp"
#include "Group.hpp"
#include "GroupUser.hpp"
#include<iostream>
using namespace std;

//创建群组，多对多的关系，用两张表维护，一张维护群组信息（一个多对多的关系），一张维护成员和群组关系（1对1关系）
bool GroupModel::create_group(Group& group){
    //组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "insert into ALLgroup(groupname, groupdesc) values('%s','%s')"
            , group.get_name().c_str(), group.get_desc().c_str());

    MySQL mysql;
    if(mysql.connect()){
        if(mysql.update(sql)){
            group.set_id(mysql_insert_id(mysql.get_connection()));//获取上次插入的id
            return true;
        }
    }
    return false;
}

//加入群组
bool GroupModel::add_group(int user_id, int group_id, std::string role){
    //组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "insert into GroupUser(groupid, userid, grouprole) values(%d, %d, '%s')", group_id, user_id, role.c_str());
    cout<< sql << endl;
    MySQL mysql;
    if(mysql.connect()){
        if(mysql.update(sql)){
            return true;
        }
    }
    return false;
}

vector<Group> GroupModel::query_group(int user_id){ 
    //组装sql语句
    char sql[1024] = {0};
    //select 语句先从：GroupUser和Group的联合表（这个表和Gruop以及GroupUser不是一一对应的）中获取组id相同的露记录, 从联合表中获取 b.userid = user_id的记录。
    sprintf(sql,"select a.id, a.groupname, a.groupdesc from ALLgroup a inner join GroupUser b on b.groupid = a.id where b.userid = %d;", user_id);
    
    vector<Group> group_vec;//所有表
    MySQL mysql;
    if(mysql.connect()){
        MYSQL_RES *res = mysql.query(sql);//获取所有记录，获取所有群组的信息。
        if(res != nullptr){
            MYSQL_ROW row;
            while((row = mysql_fetch_row(res)) != nullptr){  
                Group group;    //创建一个group对象。
                group.set_id(atoi(row[0])); //设置id
                group.set_name(row[1]);     //设置name
                group.set_desc(row[2]);
                group_vec.push_back(group);
            }
            mysql_free_result(res);
        }
    }
    
    for(Group &temp : group_vec){//遍历群组
        sprintf(sql, "select a.id, a.name, a.state, b.grouprole from user a inner join GroupUser b on b.userid = a.id where b.groupid = %d ", temp.get_id());  
        
        MYSQL_RES *res = mysql.query(sql);
        if(res  != nullptr){
            MYSQL_ROW row;
            while((row = mysql_fetch_row(res)) != nullptr){
                GroupUser group_user;
                group_user.set_id(atoi(row[0]));
                group_user.set_name(row[1]);
                group_user.set_state(row[2]);
                group_user.set_role(row[3]);
                temp.get_Users().push_back(group_user);
            }
            //释放资源，否则内存不断泄露
            mysql_free_result(res);
        }
    }
    return group_vec;
}

vector<int> GroupModel::query_group_users(int user_id, int group_id){
    //组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "select userid from GroupUser where groupid = %d and userid != %d;", group_id, user_id);
    
    vector<int> id_vec;
    MySQL mysql;
    if(mysql.connect()){ 
        MYSQL_RES *res = mysql.query(sql);
        if(res != nullptr){
            MYSQL_ROW row;
            while((row = mysql_fetch_row(res)) != nullptr){
                id_vec.push_back(atoi(row[0])); 
            }
            //释放资源，否则内存不断泄露
            mysql_free_result(res);
        }
    }
    return id_vec;
}